﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Net.Mime;
using System.Text;
using System.Threading.Tasks;

namespace TaoBaoKe.Common
{
    public class Mail
    {
        /// <summary>
        /// 发送电子邮件
        /// </summary>
        /// <param name="mailToName">收件人</param>
        /// <param name="mailServer">邮箱服务器</param>
        /// <param name="username">用户名</param>
        /// <param name="password">密码</param>
        /// <param name="mailFrom">发件人</param>
        /// <param name="subject">主体</param>
        /// <param name="body">邮件内容</param>
        /// <param name="IsHtml">是否是HTML格式</param>
        /// <returns></returns>
        public static bool SendTo(string mailToName, string mailServer, string password, string mailFrom, string subject, string body, bool IsHtml, ICollection<string> paths)
        {
            MailMessage mailMessage = new MailMessage();
            mailMessage.From = new MailAddress(mailFrom);
            mailMessage.To.Add(mailToName);
            mailMessage.Subject = subject;
            mailMessage.IsBodyHtml = IsHtml;
            mailMessage.Body = body;
            mailMessage.BodyEncoding = Encoding.UTF8;
            if (paths!=null&&paths.Count>0)
            {
                IEnumerator<string> ie = paths.GetEnumerator();
                    while (ie.MoveNext())
                    {
                        mailMessage.Attachments.Add(new Attachment(ie.Current));
                    }
                
            }
            SmtpClient smtpClient = new SmtpClient();
            smtpClient.Host = mailServer;
            smtpClient.Credentials = new NetworkCredential(mailFrom, password);
            try
            {
                smtpClient.Send(mailMessage);
                return true;
            }
            catch(Exception e)
            {
                Log.txtLog(@"D:\系统源代码\TaoBaoKe\TaoBaoKe\log\email.log",e.Message);
                return false;
            }
        }
    }
}
